<?php
/**
 * 获取地区信息
 * 例如： 
 *      ?m=Api/Region&field=province&value=福建省
 *      ?m=Api/Region&field=city&value=厦门市&province=福建省
 *      ?m=Api/Region&field=area&value=思明区&province=福建省&city=思明区
 *
 * @author Alen
 * @since 1.0.0 2013-5-22 sutroon
 */
class RegionAction extends SoAction {

    //put your code here
    public function index() {
        $field = $wu->request_string('field');
        $value = $wu->request_string('value');
        $province = $wu->request_string('province');
        $city = $wu->request_string('city');
        $area = $wu->request_string('area');

        if (!$field)
            exit('<option>参数错误</option>');

        $doc = new DOMDocument();
        if (!$doc->load('Sites/AppRes/CnRegion/region-cn-min.xml'))
            exit('地区XML文件不存在');

        $selected = '';
        $v = '';

        // 省份
        if ($field == 'province') {
            $nodes = $doc->getElementsByTagName('province');
            foreach ($nodes as $a) {
                $v = $a->getAttribute('name');
                $selected = ($value && $value == $v) ? ' selected="selected"' : '';
                echo '<option value="' . $v . '"' . $selected . '>' . $v . '</option>';
            }
            exit();
        }

        // 城市
        if ($field == 'city') {
            $xpath = new DOMXPath($doc);
            $nodes = $xpath->query('province[@name="' . $province . '"]/city');
            if (!$nodes)
                exit('<option>未找到符合的城市</option>');
            foreach ($nodes as $a) {
                $v = $a->getAttribute('name');
                $selected = ($value && $value == $v) ? ' selected="selected"' : '';
                echo '<option value="' . $v . '"' . $selected . '>' . $v . '</option>';
            }
            exit();
        }
        // 地区
        if ($field == 'area') {
            $xpath = new DOMXPath($doc);
            $nodes = $xpath->query('province[@name="' . $province . '"]/city[@name="' . $city . '"]/area');
            if (!$nodes)
                exit('<option>未找到符合的地区</option>');
            foreach ($nodes as $a) {
                $v = $a->getAttribute('name');
                $selected = ($value && $value == $v) ? ' selected="selected"' : '';
                echo '<option value="' . $v . '"' . $selected . '>' . $v . '</option>';
            }
            exit();
        }
    }

}

?>
